package com.samphanie.admin.aspect;

import cn.hutool.json.JSONUtil;
import com.samphanie.admin.annotation.SaveLog;
import com.samphanie.admin.modules.sys.service.ISysLogService;
import com.samphanie.common.utils.RequestHolder;
import com.samphanie.mbg.model.sys.SysLog;
import com.samphanie.security.utils.SecurityUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;


/**
 * 系统日志，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class LogAspect {

    @Resource
    private ISysLogService sysSaveLogService;

    @Pointcut("@annotation(com.samphanie.admin.annotation.SaveLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveSysLog(point, time);

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysSaveLog = new SysLog();
        SaveLog syslog = method.getAnnotation(SaveLog.class);
        if (syslog != null) {
            //注解上的描述
            sysSaveLog.setOperation(syslog.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysSaveLog.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        try {
            String params = JSONUtil.toJsonStr(args);
            sysSaveLog.setParams(params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置IP地址
        String ipAddress = RequestHolder.getHttpServletRequestIpAddress();
        sysSaveLog.setIp(ipAddress);

        // TODO 用户名
        sysSaveLog.setUsername(SecurityUtil.getCurrentUsername());
        sysSaveLog.setTime(time);
        //保存系统日志
        sysSaveLogService.save(sysSaveLog);
    }
}
